import { Component, OnInit, HostListener, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";
import { ApiService } from "../../../../environments/environment";
import { OrganizationService } from "../../../service/organization.service";
import { RequestOptionsArgs } from "@angular/http";
import { TreeNode } from "primeng/components/common/treenode";

@Component({
  selector: 'app-entry-permission',
  templateUrl: './entry-permission.component.html',
  styleUrls: ['./entry-permission.component.css']
})
export class EntryPermissionComponent   implements OnInit {
  persondepartments : TreeNode[] ;
  selectingdepartment : TreeNode ;  
  persons: any[];
  selectingpersons: any[];

  selecteddepersons = [] ;//最终选项
  selectingpersons2 : any[];
  personname:string;
  departmentstyle;
  constructor( public dialogRef: MatDialogRef<EntryPermissionComponent>,@Inject(MAT_DIALOG_DATA) private callerData: any,private organization: OrganizationService
  ,private api: ApiService) {
      this.departmentstyle={'height':'200px','margin-top':'5px','width':'415px'};
  }

  ngOnInit() {
    this.organization.GetTreeData().then(items=>{
      this.persondepartments=items;
      if(items.length)
        this.selectingdepartment=items[0];
    });

  }

  GetPerson(event){
    this.api.Info.GetEmployeeList(this.selectingdepartment.data.id).then(persons=>{
      this.persons=persons;
    })
  }

  SerchPerson(name:string){
    let option: RequestOptionsArgs = { params: {} };
    if (name) option.params['name'] = name;
    let departmentid = 0;
    if (this.selectingdepartment) departmentid = this.selectingdepartment.data.id;
    this.api.Info.GetEmployeeList(departmentid,option).then(persons=>{
      this.persons=persons;
    })
  }

  cancel() {
    this.dialogRef.close();
  }

  save() {
    let useids=this.selecteddepersons.map(item=>item.id);
    this.api.EntryPower.AddUsers({entryAreaId:this.callerData.id,userIds:useids}).then(()=>{
      this.dialogRef.close(true);
    });
  }


  AddPerson(){
    if (this.selectingpersons && this.selectingpersons.length) {
      this.selectingpersons.forEach((item, index) => {
        this.selecteddepersons.push(item);
      });
      let existitem:any={};
      this.selecteddepersons = this.selecteddepersons.filter((item) => {
        if (existitem[item.id])
          return false;
        else {
          existitem[item.id] = true;
          return true;
        }
      });
    }
  }

  DelPerson(){
    if(this.selectingpersons2 && this.selectingpersons2.length){
      let curselected = this.selectingpersons2;
      this.selecteddepersons = this.selecteddepersons.filter(item=>!curselected.find(s=>s.id==item.id))
    }
  }

}
